using System;
using System.Data;

namespace FreeFlow.Administration
{
	/// <summary>
	/// A user attribute.
	/// </summary>
	public class UserAttribute : DatabaseAware, IDeletable, IUpdatable
	{
    internal UserAttribute(Server server, IDataReader reader) : base(server)
    {
      user = reader["eUserName"].ToString();
      name = reader["eAttribute"].ToString();
      oldName = name;
      value = reader["eValue"].ToString();
      oldValue = value;
    }

    /// <summary>
    /// Initializes a new instance of the <see cref="UserAttribute"/> class.
    /// </summary>
    /// <param name="server">The database server.</param>
    /// <param name="user">The user for whom this is an attribute.</param>
    public UserAttribute(Server server, string user) : base(server)
    {
      this.user = user;
    }

    private string user;
    /// <summary>
    /// Gets the user for whom this is an attribute.
    /// </summary>
    /// <value>The user.</value>
    public string User
    {
      get
      {
        return user;
      }
    }

    private string oldName = "";
    private string name;
    /// <summary>
    /// Gets or sets the name of the attribute.
    /// </summary>
    public string Name
    {
      get
      {
        return name;
      }
      set
      {
        name = value;
      }
    }

    private string oldValue = "";
    private string value;
    /// <summary>
    /// Gets or sets the value of the attribute.
    /// </summary>
    public string Value
    {
      get
      {
        return value;
      }
      set
      {
        this.value = value;
      }
    }

    #region IDeletable Members

    /// <summary>
    /// Deletes this attribute from the database.
    /// </summary>
    public void Delete()
    {
      Server.ExecuteNonQuery(string.Format("DELETE FROM eAttribute WHERE eUserName = '{0}' AND eAttribute='{1}' AND eValue='{2}'",
        SqlEscape(user), SqlEscape(name), SqlEscape(value)));
    }

    #endregion
    #region IUpdatable Members

    /// <summary>
    /// Applies the changes made to this attribute.
    /// </summary>
    public void ApplyChanges()
    {
      if (string.IsNullOrEmpty(oldName) && string.IsNullOrEmpty(oldValue))
      {
        // new attribute
        Server.ExecuteNonQuery(string.Format("INSERT INTO eAttribute (eUserName, eAttribute, eValue) VALUES ('{0}', '{1}', '{2}')",
          SqlEscape(user), SqlEscape(name), SqlEscape(value)));
      }
      else
      {
        // old attribute 
        Server.ExecuteNonQuery(string.Format("UPDATE eAttribute SET eAttribute='{0}', eValue='{1}' WHERE eUserName = '{2}' AND eAttribute='{3}' AND eValue='{4}'",
          SqlEscape(name), SqlEscape(value), SqlEscape(user), SqlEscape(oldName), SqlEscape(oldValue)));
      }
    }

    #endregion
  }
}
